<template>
  <div>
    <!-- 表单校验 -->
    <!-- :rules="rules" -->
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="labelWidth || '120px'"
      class="demo-ruleForm"
      :inline="true"
    >
      <el-row :gutter="10" :span="24">
        <!-- <el-col v-bind="formRowColSpan"> -->
        <el-col
          :xs="24"
          :sm="12"
          :md="12"
          :lg="8"
          v-for="item in formOptions"
          :key="item.prop"
        >
          <!-- <el-col :span="12"> -->
          <el-form-item
            style="width: 100%"
            :label="item.label"
            :prop="item.prop"
          >
            <component
              :is="comps[item.type]"
              v-model="form[item.prop]"
              :option="item"
            ></component>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="display: flex; justify-content: flex-end">
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >搜索</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  PropType,
  reactive,
  watch,
  ref,
  getCurrentInstance,
  ComponentInternalInstance,
} from 'vue';
import type { IFromItem, IrowCol } from '@/views/main/system/user/config';
import type { FormInstance } from 'element-plus';

const ctx = require.context('./components', true, /\.vue/);
const comps = ctx.keys().reduce((pre, cur) => {
  // console.log(el, el.split('.')[1]);
  // console.log('./components' + el.split('.')[1]);
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  const path = require('./components' + cur.split('.')[1]);
  // console.log(path.default);
  let name = path.default.name || path.default;
  return { ...pre, [name]: path.default };
}, {});
// console.log(comps);

export default defineComponent({
  name: 'XMForm',
  components: {},
  props: {
    formOptions: {
      type: Array as PropType<IFromItem[]>,
      default: () => [],
    },
    formRowColSpan: {
      type: Object as PropType<IrowCol>,
    },
    modelValue: Object,
    labelWidth: [String],
    rules: {
      type: Object,
    },
  },
  emits: ['update:modelValue', 'search', 'reset'],
  // eslint-disable-next-line
  setup(props, { attrs, slots, emit, expose }) {
    // console.log('XMForm', props.modelValue);
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const form = reactive({ ...props.modelValue });
    const ruleFormRef = ref<FormInstance>();

    // const { ctx: that } = getCurrentInstance() as ComponentInternalInstance;
    // console.log(that);
    const oldFormData = { ...props.modelValue };

    const handleForm = watch(
      form,
      // eslint-disable-next-line
      (val, oldVal) => {
        emit('update:modelValue', val);
        // console.log('form变了', val);
      },
      {
        deep: true,
      },
    );

    const submitForm = async (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          // console.log('submit!');
          emit('search');
        } else {
          console.log('error submit!', fields);
        }
      });
    };

    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
      // Object.keys(oldFormData).forEach((key: string) => {
      //   form[key] = oldFormData[key];
      // });
      // that.$forceUpdate();
      emit('reset');
    };

    return {
      comps,
      form,
      ruleFormRef,
      handleForm,
      submitForm,
      resetForm,
    };
  },
});
</script>

<style scoped lang="less">
// @import 'element-plus/theme-chalk/el-row.css';
// @import 'element-plus/theme-chalk/el-col.css';
// div {
//   display: flex;
//   justify-content: flex-end;
// }
</style>
